package com.zygh.lz.task;

import com.zygh.lz.dao.PatrolrecordMapper;
import com.zygh.lz.dao.SignMapper;
import com.zygh.lz.entity.Patrolrecord;
import com.zygh.lz.entity.Sign;
import com.zygh.lz.entity.duty.DutySchedule;
import com.zygh.lz.service.DutyScheduleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author lee
 * 全天班
 */
@Lazy(false)
@Component
@EnableScheduling
@Slf4j
public class AllDayTask implements SchedulingConfigurer {
    @Resource
    private SignMapper signMapper;
    @Resource
    private PatrolrecordMapper patrolrecordMapper;
    @Resource
    private DutyScheduleService dutyScheduleService;
    // 默认的cron表达式
    private String cron = "0 30 20 * * ?";

    // 定时任务的执行顺序：由上而下按顺序执行，当服务启动时或者定时任务时间到了，先执行业务逻辑，再设置定时任务
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(() -> {
            // addTriggerTask这一代码块用于当定时任务到了或者服务启动时，执行的业务逻辑
            this.recordOutput();
        }, triggerContext -> {
            // 此代码块用于动态拿到cron表达式并设置定时任务，当定时任务时间到了，就会重新获取cron表达式，重新设置定时任务
            cron = this.getCronString();
            CronTrigger trigger;
            try {
                // 一旦设置，立即生效
                trigger = new CronTrigger(cron);
                return trigger.nextExecutionTime(triggerContext);
            } catch (Exception e) {
                // 如果格式有问题就按默认时间
                trigger = new CronTrigger("0 30 20 * * ?");
                return trigger.nextExecutionTime(triggerContext);
            }
        });
    }

    /**
     * 拿到cron表达式
     */
    private String getCronString() {
        //  数据库获取cron表达式
        DutySchedule one = dutyScheduleService.findOne(3, 0);
        if (Objects.nonNull(one)) {
            String cron = one.getCron();
            return cron;
        }
        return cron;
    }

    /**
     * shiftop 5 早高峰 6 晚高峰
     * 处理签退业务
     */
    private void recordOutput() {
        log.info("全天班自动签退执行");
        DutySchedule one = dutyScheduleService.findOne(3, 0);
        Sign sign = new Sign();
        List<Map> mapList = signMapper.OnlineAll();
        for (Map map : mapList) {
            if(Objects.isNull(map.get("modeCode"))){
                continue;
            }
            Integer modeCode = Integer.valueOf(String.valueOf(map.get("modeCode")));
            String comment = map.get("comment").toString();
            if (Objects.equals(one.getModeCode(), modeCode) && "1".equals(comment)) {
                sign.setId(Integer.valueOf(map.get("id").toString()))
                        .setSignouttime(cn.hutool.core.date.DateUtil.now())
                        .setState(2);
                signMapper.updateByPrimaryKeySelective(sign);
                updatePatrole(map.get("signnum").toString());
            }

        }
    }

    private void updatePatrole(String signnum) {
        Patrolrecord patrolRecordOne = patrolrecordMapper.findPatrolRecordOne(signnum);
        if (patrolRecordOne != null) {
            patrolRecordOne.setPatrolRecordEndtime(new Date());
            patrolrecordMapper.updateByPrimaryKeySelective(patrolRecordOne);
        }

    }
}